var pageSize = 25;

//create data store
var dataStore = new Ext.data.Store(
    {
        proxy: new Ext.data.HttpProxy
        (
            { url: base_url + '/users/ajax-fetch-users/' }
        ),

        reader: new Ext.data.JsonReader
        (
            { root: 'users', totalProperty: 'count', id: 'id' },
            [
                { name: 'id', mapping: 'id' },
                { name: 'name', mapping: 'name' },
                { name: 'login', mapping: 'login' },
                { name: 'email', mapping: 'email' },
                { name: 'groups', mapping: 'groups' },
            ]
        ),
    }
);

// create the Grid
var grid = new Ext.grid.GridPanel({
    store: dataStore,
    columns: 
    [
        { id:'id', header: "Id", width: 50, sortable: true, dataIndex: 'id'},
        { id:'name', header: "Name", width: 100, sortable: true, dataIndex: 'name'},
        { id:'login', header: "Login", width: 100, sortable: true, dataIndex: 'login'},
        { id:'email', header: "E-mail", width: 100, sortable: true, dataIndex: 'email'},
        { id:'gropus', header: "Groups", width: 150, renderer: renderGroups, sortable: false, dataIndex: 'groups'},
        { header: 'Edit', width:50, renderer: renderEdit, align: 'center', sortable: false, dataIndex: 'id'},
        { header: 'Delete', width:50, renderer: renderDelete, align: 'center', sortable: false, dataIndex: 'id'},
    ],
    stripeRows: true,
    height:300,
    width:650,
    title:'Users Grid',
	bbar: new Ext.PagingToolbar({
	    pageSize:       pageSize,
	    store:          dataStore,
	    displayInfo:    true,
	    displayMsg:     'Results {0} - {1} of {2}',
	    emptyMsg:       'No results'
	}),    
});

function renderGroups(value, p, record) {
    var cnt = value.length;
    var gr = '';
    
    for (var i = 0; i < cnt; i++) {
    	gr = gr + value[i]['name'] + ', ';
    }
    
    return gr.slice(0, -2);
}
 
function renderEdit(value, p, record) {
    return String.format('<img src="images/common/fico_modify.gif" style="margin-left: 2px; cursor: pointer" onclick="javascript:editRow({0})" />', value );
}

function renderDelete(value, p, record) {
    return String.format('<img src="images/common/fico_trash.gif" style="margin-left: 2px; cursor: pointer" onclick="javascript:deleteRow({0})" />', value );
}
    
function editRow(id) {
    window.location.href = base_url + '/users/edit/id/' + id;
}

function deleteRow(id) {
    window.location.href = base_url + '/users/delete/id/' + id;
}
       
function reloadGrid(group_id)
{
    //send request and render the grid
    dataStore.load({
    	params: {
    		start: 0,
    		limit: pageSize,
    		group_id:group_id
    	}
    });
    grid.render('user-grid');
}